def find_max_overlap_position(S1, S2):
    # 统计S2中字符的数量
    char_count_S2 = {}
    for char in S2:
        char_count_S2[char] = char_count_S2.get(char, 0) + 1

    # 初始化用于滑动窗口的变量
    max_overlap = 0
    start_position = -1
    current_window_count = {}

    # 遍历S1
    for end in range(len(S1)):
        end_char = S1[end]
        current_window_count[end_char] = current_window_count.get(end_char, 0) + 1

        # 检查当前窗口内的字符是否满足条件
        while all(current_window_count.get(char, 0) >= char_count_S2[char] for char in char_count_S2):
            window_size = end - start_position
            if window_size > max_overlap:
                max_overlap = window_size
                max_start_position = start_position + 1

            start_position += 1
            start_char = S1[start_position]
            current_window_count[start_char] -= 1

    return max_start_position


# 示例
S1 = "abcdefg"
S2 = "bdf"
print(find_max_overlap_position(S1, S2))
